package com.ifonly.plugin;

import com.ifonly.common.ClassScanner;
import com.ifonly.config.Configuration;
import com.ifonly.core.ClassContainer;
import com.ifonly.mvc.ActionMapper;
import com.ifonly.mvc.Controller;
import com.ifonly.mvc.helpers.ActionMappingHelper;
import com.ifonly.reports.Reporter;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-16 09:41
 * @since JDK 1.6
 */
public class DevPlugin implements Plugin {
    private final ActionMapper actionMapper = ActionMapper.getInstance();
    private final ClassContainer classContainer = ClassContainer.getInstance();
    private Configuration cfg = Configuration.getInstance();
    private Timer timer;

    @Override
    @SuppressWarnings("unchecked")
    public boolean start() {
        final Reporter reporter = cfg.getReporter();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                synchronized (actionMapper) {
                    try {
                        reporter.report("DevPlugin load context.....");
                        List<Class<?>> list =  ClassScanner.of("app").scan();
                        classContainer.fillGroup(list);

                        List<Class<?>> controllerClasses = classContainer.group(Controller.class);
                        if (controllerClasses != null && !controllerClasses.isEmpty()) {
                            for (Class<?> clazz : controllerClasses) {
                                Class<? extends Controller> controllerClass = (Class<? extends Controller>) clazz;
                                ActionMappingHelper.controllerActionMapping(controllerClass, actionMapper, true);
                            }
                        }

                        //Sql.init();

                        classContainer.destroy();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        };
        //timer = new Timer();
        //timer.schedule(timerTask, 5000, 5000);
        return true;
    }

    @Override
    public boolean stop() {
        timer.cancel();
        timer = null;
        return true;
    }

}
